package grape.file.service.cloudstorage.impl;

import cn.hutool.core.io.IoUtil;
import cn.hutool.http.HttpUtil;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import grape.common.tools.IoStreamTool;
import grape.common.tools.PathTool;
import grape.file.service.cloudstorage.config.QiniuStorageConfig;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;

/**
 * @Auther: wzn
 * @Date: 2019/2/20 15:41
 * @Description: 七牛云存储
 */
@Service
public class QiniuCloudStorageServiceImpl extends AbstractCloudStorageService implements InitializingBean {
    private static Logger logger = LoggerFactory.getLogger(QiniuCloudStorageServiceImpl.class);
    @Autowired
    private QiniuStorageConfig config;

    private UploadManager uploadManager;
    private String token;
    private Auth auth;

    @Override
    public void afterPropertiesSet() throws Exception {
        // 如果没有配置不初始化，保证应用能起来
        if (config.getAccessKey() == null) {
            return;
        }
        uploadManager = new UploadManager(new Configuration(Zone.autoZone()));
        auth = Auth.create(config.getAccessKey(), config.getSecretKey());
        token = auth.uploadToken(config.getBucketName());
    }

    @Override
    public boolean support(String type) {
        return isEqual(config.uploadType(),type);
    }

    @Override
    public String upload(byte[] data, String filepath) {
        try {
            Response res = uploadManager.put(data, PathTool.concat(config.getPrefix() , filepath), token);
            if (!res.isOK()) {
                throw new RuntimeException("上传七牛出错："+res.toString());
            }
        } catch (Exception e) {
            throw new RuntimeException("上传文件失败，请核对七牛配置信息," + e.getMessage(),e);
        }

        return getResult(config.getDomain(),config.getPrefix() , filepath);
    }

    @Override
    public String uploadSuffix(byte[] data,String prefixPath, String suffix) {
        return upload(data, newPath(PathTool.concat( prefixPath), suffix));
    }

    @Override
    public String upload(InputStream inputStream, String filepath) {
        try {
            byte[] data = IOUtils.toByteArray(inputStream);
            return this.upload(data, filepath);
        } catch (IOException e) {
            throw new RuntimeException("七牛上传文件失败," + e.getMessage(),e);
        }
    }

    @Override
    public String uploadSuffix(InputStream inputStream,String prefixPath, String suffix) {
        return upload(inputStream, newPath(PathTool.concat( prefixPath), suffix));
    }

    @Override
    public byte[] download(String objectName) throws IOException {
        String downloadUrl = auth.privateDownloadUrl(PathTool.concat(config.getDomain(), objectName));
        return IoStreamTool.inputStreamToByteArray(HttpUtil.createGet(downloadUrl).execute().bodyStream());
    }

    @Override
    public int delete(String objectName) {

        // 暂未实现参考https://developer.qiniu.com/kodo/api/1257/delete
        return 0;
    }

}
